// pages/coursevideo/coursevideo.js
const config = require("../../config");
function getRandomColor() {
  const rgb = []
  for (let i = 0; i < 3; ++i) {
    let color = Math.floor(Math.random() * 256).toString(16)
    color = color.length === 1 ? '0' + color : color
    rgb.push(color)
  }
  return '#' + rgb.join('')
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    videoId: '',
    videoSrc: '',
    video: {},
    commentList: null,
    danmu: {},
    danmuList: [
      {color: "#75e972",
      text: "34",
      time: "3"},
      {color: "#75e972",
      text: "34",
      time: 5},
      {color: "#75e972",
      text: "34",
      time: "12"},
    ],
    text: '',

    //实时记录时间
    currentTime:0,

    src: '',
    dianzan1:"../../icon/shoucang.png",
    dianzan2:"../../icon/shoucang.png",
    icon_uri:null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log(options)
    this.setData({
      videoId: options.videoId
    })
    this.getVideo(options.videoId);
    this.getCommentList();
    this.setData({
      danmuList: this.data.danmuList,
    })
  },

  /**
   * 获取视频资源
   */
  getVideo(id) {
    wx.request({
      url: `http://127.0.0.1:8080/coursevideo/${config.userId}/detail?videoId=${id}`,
      success: (res) => {
        console.log(res);
        this.setData({
          video: res.data.data,
          videoSrc: 'http://127.0.0.1:8080/common/downloadvideo?name=' + res.data.data.videoUri,
          icon_uri:res.data.data.liked==1?this.data.dianzan1:this.data.dianzan2
        })
      }
    })
  },

  onProgress(e){
 // e.detail.currentTime 当前播放的时间
    // e.detail.duration 视频的总时长
    // e.detail.playedSeconds 已经播放的秒数
    // e.detail.timeStamp 事件触发的时间戳
    // console.log(e.detail.currentTime);
    this.setData({
      currentTime:e.detail.currentTime
    })
    // 你可以根据需要处理播放进度
  },

  handleProgressChange(e) {
    // 获取用户拖动后的进度位置（单位为秒）
    var currentTime = e.detail.currentTime;
    // 可以在这里进行一些处理，比如更新UI显示新的进度位置
    console.log("当前播放时间：", currentTime);
  },
  /**
   * 获取评论列表
   */
  getCommentList() {
    wx.request({
      url: `http://127.0.0.1:8080/courseComments/${config.userId}/list?videoId=${this.data.videoId}`,
      success: (res) => {
        console.log(res.data.data);
        if (res.data.code == 1) {
          this.setData({
            danmuList: res.data.data
          })
        }
        console.log(this.data.danmuList);
      }
    })
  },


  /**
 * 评论输入框内容改变，绑定内容
 */
  commentInput(e) {
    console.log(  e.detail.value);
    this.setData({
      text: e.detail.value
    });
    console.log("text:" + this.data.text);

  },

  /**
   *  发送弹幕到数据库
   */
  submit() {
    if (this.data.text) {
      wx.request({
        url: `http://127.0.0.1:8080/courseComments/${config.userId}/publish`,
        method: 'POST',
        data: {
          videoId: this.data.videoId,
          time:this.data.currentTime,
          text: this.data.text,
          color:getRandomColor(),
        },
        success: (res) => {
          console.log(res);
          if (res.data.code == 1) {
            this.bindSendDanmu()
          }
        }
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    this.videoContext = wx.createVideoContext('myVideo');
  },

  bindButtonTap() {
    const that = this
    wx.chooseVideo({
      sourceType: ['album', 'camera'],
      maxDuration: 60,
      camera: ['front', 'back'],
      success(res) {
        that.setData({
          src: res.tempFilePath
        })
      }
    })
  },

  bindVideoEnterPictureInPicture() {
    console.log('进入小窗模式')
  },

  bindVideoLeavePictureInPicture() {
    console.log('退出小窗模式')
  },

  bindPlayVideo() {
    console.log('1')
    this.videoContext.play()
  },
  bindSendDanmu() {
    this.videoContext.sendDanmu({
      text: this.data.text,
      color: getRandomColor()
    })
    this.setData({
      text: ''
    })
  },

  videoErrorCallback(e) {
    console.log('视频错误信息:')
    console.log(e.detail.errMsg)
  },

  shoucang(){
    wx.request({
      url: `http://127.0.0.1:8080/coursevideo/${config.userId}/like?videoId=${this.data.videoId}`,
      method: 'GET',
      success: (res) => {
        console.log(res);
        if (res.data.code == 1) {
          console.log(res.data.data);
          if(res.data.data == 1){
            console.log(res.data.data);
            this.setData({
            icon_uri:this.data.dianzan2,
          })
          wx.showToast({
            icon:"success",
            title: "取消收藏",
          })
          }else{
            console.log(res.data.data);
            this.setData({
              icon_uri:this.data.dianzan1
            })
            wx.showToast({
              icon:"none",
              title: "成功收藏",
            })
          }
          
        }
      }
    })
  }
})